package com.ivanceras.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.ivanceras.client.SimulationService;
import com.ivanceras.client.SimulationServiceAsync;
import com.ivanceras.model.Choice;
import com.ivanceras.model.Question;
import com.ivanceras.model.Questionnaire;

public class QuestionView {
	public VerticalPanel view = new VerticalPanel();
	public VerticalPanel edit = new VerticalPanel();
	public Question question;
	
	private RichTextArea area = new RichTextArea();
	private Button save = new Button("Save");
	
	private HTML text = new HTML();
	private VerticalPanel choicePanel = new VerticalPanel();

	private final SimulationServiceAsync simulationService = GWT
	.create(SimulationService.class);
	
	public QuestionView(){
		initLayout();
		initHandlers();
	}
	public void initLayout(){
		view.add(text);
		edit.add(area);
		edit.add(choicePanel);
		edit.add(save);
	}
	public void initHandlers(){
		area.addKeyUpHandler(new KeyUpHandler(){

			@Override
			public void onKeyUp(KeyUpEvent event) {
				question.text = area.getHTML();
			}
			
		});
		save.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				simulationService.saveQuestion(question,
						new AsyncCallback<Question>(){

							@Override
							public void onFailure(Throwable caught) {
								Window.alert("Error saving question");
							}

							@Override
							public void onSuccess(Question result) {
								System.out.println("Sucess saving question");
							}
					
				});

			}
			
		});
	}
	public void setQuestion(Question qn){
		this.question = qn;
		text.setHTML(qn.text);
		area.setHTML(qn.text);
		for(Choice ch : qn.choiceList){
			ChoiceView chv = new ChoiceView();
			chv.setChoice(ch);
			view.add(chv.view);
			choicePanel.add(chv.edit);
		}
		
	}
}
